import path from "path";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import Inspect from "vite-plugin-inspect";
import Components from "unplugin-vue-components/vite";
import os from "os";
import { fileURLToPath, URL } from "node:url";
import { defineConfig, loadEnv } from "vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { visualizer } from "rollup-plugin-visualizer";
import { VitePWA } from "vite-plugin-pwa";
// 自定义配置
import autoImportFn from "./src/plugin/autoImport";
import { autoSelfComponent } from "./src/plugin/autoSelfComponent";

// 获取当前主机 IPv4
const net = os.networkInterfaces();
const ipv4Address = (net["以太网"] || net["WLAN"])?.filter(
  (_) => _.family === "IPv4"
)[0].address;
const getPath = (): string => fileURLToPath(new URL("./src", import.meta.url));

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  // 读取环境配置
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV } = env;
  return {
    base: VITE_APP_ENV === "production" ? "/" : "/",
    plugins: [
      vue({
        template: {
          compilerOptions: {
            isCustomElement: (tag) => tag.includes("my-web-"), // webComponents 配置
          },
        },
      }),
      visualizer({
        // 打包分析：打包完成后会弹出一个网页显示各个依赖的大小占比，生成 stats.html
        open: true,
      }),
      /**
       * PWA 技术的出现就是让web网页无限接近于Native 应用
          可以添加到主屏幕，利用manifest实现
          可以实现离线缓存，利用service worker实现
          可以发送通知，利用service worker实现
       */
      VitePWA({
        // vite打包优化：生成sw.js
        workbox: {
          cacheId: "cache", //缓存名称
          runtimeCaching: [
            {
              urlPattern: /.*\.js.*/, //缓存文件
              handler: "StaleWhileRevalidate", //重新验证时失效
              options: {
                cacheName: "cache-js", //缓存js，名称
                expiration: {
                  maxEntries: 30, //缓存文件数量 LRU算法
                  maxAgeSeconds: 30 * 24 * 60 * 60, //缓存有效期
                },
              },
            },
          ],
        },
      }),
      AutoImport({
        imports: autoImportFn() as any, // 自动引入 Vue3 的 Composition API
        dirs: ["./src/utils", "./src/common", "./src/components", './src/api'], // 自动导入自定义函数
        resolvers: [
          // 引入ELement Plus
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({
            prefix: "Icon",
          }),
        ],
        dts: path.resolve("./src", "auto-imports.d.ts"),
      }),
      Components({
        dirs: ["./src/components"], // 自动导入自定义组件
        resolvers: [
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ["ep"], // 使用 i-ep-Xxx
          }),
          ElementPlusResolver(),
          // 自定义配置自动导入
          {
            type: "component",
            resolve: (componentName: string) =>
              autoSelfComponent(componentName),
          },
        ],
        dts: path.resolve("./src", "auto-component.d.ts"),
      }),
      Icons({
        autoInstall: true,
      }),
      Inspect(),
    ],
    resolve: {
      alias: {
        "@": getPath(), // 配置文件别名路径
      },
      extensions: [".js", ".jsx", ".ts", ".tsx", ".json", ".vue"], // 配置文件后缀省略
    },
    // CSS 预解析
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "./src/assets/scss/index.scss";`,
          javascriptEnabled: true, // 开启JS引用SCSS变量
        },
      },
    },
    // 内置服务配置
    server: {
      port: 3000,
      host: true,
      open: false,
      // 代理配置
      proxy: {
        "/dev-api": {
          target: `http://${ipv4Address}:8000`,
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, ""),
        },
      },
    },
  };
});
